<template>
  <div class="document-templates">
    <!-- 页面头部 -->
    <header class="page-header">
      <div class="header-content">
        <div class="header-left">
          <h1 class="page-title">文书模板</h1>
          <p class="page-subtitle">法律文书模板库，提供各类法律文书模板</p>
        </div>
        <div class="header-actions">
          <el-button type="primary" @click="showUploadDialog = true">
            <i class="fas fa-plus mr-2"></i>上传模板
          </el-button>
          <el-button @click="refreshData">
            <i class="fas fa-sync-alt mr-2"></i>刷新
          </el-button>
        </div>
      </div>
    </header>

    <!-- 分类导航 -->
    <div class="category-nav">
      <div class="category-tabs">
        <div
          v-for="category in categories"
          :key="category.key"
          class="category-tab"
          :class="{ active: activeCategory === category.key }"
          @click="setActiveCategory(category.key)"
        >
          <i :class="category.icon"></i>
          <span>{{ category.name }}</span>
          <span class="count">{{ getCategoryCount(category.key) }}</span>
        </div>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="filter-section">
      <div class="filter-content">
        <div class="search-box">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索模板名称、关键词..."
            size="large"
            clearable
          >
            <template #prefix>
              <i class="fas fa-search"></i>
            </template>
          </el-input>
        </div>
        
        <div class="filter-controls">
          <el-select v-model="filters.format" placeholder="文件格式" clearable>
            <el-option label="Word文档" value="docx"></el-option>
            <el-option label="PDF文档" value="pdf"></el-option>
            <el-option label="Excel表格" value="xlsx"></el-option>
            <el-option label="纯文本" value="txt"></el-option>
          </el-select>
          
          <el-select v-model="filters.difficulty" placeholder="复杂度" clearable>
            <el-option label="简单" value="easy"></el-option>
            <el-option label="中等" value="medium"></el-option>
            <el-option label="复杂" value="hard"></el-option>
          </el-select>
          
          <el-button type="primary" @click="applyFilters">筛选</el-button>
          <el-button @click="clearFilters">重置</el-button>
        </div>
      </div>
    </div>

    <!-- 模板列表 -->
    <div class="templates-section">
      <div class="templates-grid">
        <div
          v-for="template in filteredTemplates"
          :key="template.id"
          class="template-card"
          @click="previewTemplate(template)"
        >
          <div class="template-header">
            <div class="template-icon">
              <i :class="getFormatIcon(template.format)"></i>
            </div>
            <div class="template-actions">
              <el-dropdown @command="handleAction">
                <span class="el-dropdown-link">
                  <i class="fas fa-ellipsis-v"></i>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item :command="{ action: 'download', template }">
                      <i class="fas fa-download mr-2"></i>下载
                    </el-dropdown-item>
                    <el-dropdown-item :command="{ action: 'edit', template }">
                      <i class="fas fa-edit mr-2"></i>编辑
                    </el-dropdown-item>
                    <el-dropdown-item :command="{ action: 'copy', template }">
                      <i class="fas fa-copy mr-2"></i>复制
                    </el-dropdown-item>
                    <el-dropdown-item :command="{ action: 'delete', template }" divided>
                      <i class="fas fa-trash mr-2"></i>删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
          
          <div class="template-content">
            <h3 class="template-title">{{ template.name }}</h3>
            <p class="template-description">{{ template.description }}</p>
            
            <div class="template-meta">
              <div class="meta-item">
                <i class="fas fa-tag"></i>
                <span>{{ getCategoryName(template.category) }}</span>
              </div>
              <div class="meta-item">
                <i class="fas fa-file"></i>
                <span>{{ template.format.toUpperCase() }}</span>
              </div>
              <div class="meta-item">
                <i class="fas fa-download"></i>
                <span>{{ template.downloads }}次下载</span>
              </div>
            </div>
            
            <div class="template-footer">
              <div class="template-tags">
                <el-tag
                  v-for="tag in template.tags"
                  :key="tag"
                  size="small"
                  class="tag-item"
                >
                  {{ tag }}
                </el-tag>
              </div>
              <div class="template-date">
                {{ formatDate(template.updatedAt) }}
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[12, 24, 48]"
          :total="filteredTemplates.length"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </div>

    <!-- 上传模板对话框 -->
    <el-dialog v-model="showUploadDialog" title="上传文书模板" width="60%">
      <el-form :model="newTemplate" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="模板名称">
              <el-input v-model="newTemplate.name" placeholder="请输入模板名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模板分类">
              <el-select v-model="newTemplate.category" placeholder="请选择分类" style="width: 100%">
                <el-option
                  v-for="category in categories"
                  :key="category.key"
                  :label="category.name"
                  :value="category.key"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="模板描述">
          <el-input
            v-model="newTemplate.description"
            type="textarea"
            :rows="3"
            placeholder="请输入模板描述"
          ></el-input>
        </el-form-item>
        
        <el-form-item label="标签">
          <el-input
            v-model="newTemplate.tagsInput"
            placeholder="请输入标签，用逗号分隔"
          ></el-input>
        </el-form-item>
        
        <el-form-item label="上传文件">
          <el-upload
            class="upload-demo"
            drag
            action="#"
            :before-upload="handleFileUpload"
            :show-file-list="false"
          >
            <i class="fas fa-cloud-upload-alt"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">支持 doc/docx/pdf/xlsx/txt 格式</div>
          </el-upload>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showUploadDialog = false">取消</el-button>
        <el-button type="primary" @click="uploadTemplate">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import dayjs from 'dayjs'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'DocumentTemplates',
  setup() {
    const router = useRouter()
    
    // 响应式数据
    const searchKeyword = ref('')
    const activeCategory = ref('all')
    const currentPage = ref(1)
    const pageSize = ref(12)
    const showUploadDialog = ref(false)
    
    const filters = reactive({
      format: '',
      difficulty: ''
    })
    
    const newTemplate = reactive({
      name: '',
      category: '',
      description: '',
      tagsInput: '',
      file: null
    })
    
    // 分类配置
    const categories = [
      { key: 'all', name: '全部', icon: 'fas fa-folder' },
      { key: 'lawsuit', name: '起诉状', icon: 'fas fa-file-alt' },
      { key: 'defense', name: '答辩状', icon: 'fas fa-shield-alt' },
      { key: 'contract', name: '合同文书', icon: 'fas fa-handshake' },
      { key: 'application', name: '申请书', icon: 'fas fa-paper-plane' },
      { key: 'agreement', name: '协议书', icon: 'fas fa-file-signature' },
      { key: 'letter', name: '律师函', icon: 'fas fa-envelope' },
      { key: 'other', name: '其他', icon: 'fas fa-folder-open' }
    ]
    
    // 模拟模板数据
    const templates = ref([
      {
        id: 1,
        name: '交通事故人身损害赔偿起诉状',
        category: 'lawsuit',
        description: '专用于交通事故人身损害赔偿案件的起诉状模板，包含伤残鉴定、医疗费用等条款',
        format: 'docx',
        difficulty: 'medium',
        tags: ['交通事故', '人身损害', '起诉状'],
        downloads: 2850,
        updatedAt: '2024-01-20'
      },
      {
        id: 2,
        name: '机动车交通事故责任纠纷答辩状',
        category: 'defense',
        description: '针对交通事故责任认定争议案件的答辩状模板',
        format: 'docx',
        difficulty: 'medium',
        tags: ['交通事故', '责任认定', '答辩状'],
        downloads: 1890,
        updatedAt: '2024-01-18'
      },
      {
        id: 3,
        name: '交通事故和解协议书',
        category: 'agreement',
        description: '交通事故双方当事人和解协议书模板，包含赔偿条款和免责声明',
        format: 'docx',
        difficulty: 'easy',
        tags: ['交通事故', '和解', '协议'],
        downloads: 3200,
        updatedAt: '2024-01-15'
      },
      {
        id: 4,
        name: '交通事故财产损失鉴定申请书',
        category: 'application',
        description: '申请对交通事故中车辆等财产损失进行鉴定的申请书模板',
        format: 'docx',
        difficulty: 'easy',
        tags: ['交通事故', '财产损失', '鉴定申请'],
        downloads: 1567,
        updatedAt: '2024-01-12'
      },
      {
        id: 5,
        name: '交通事故伤残鉴定委托书',
        category: 'application',
        description: '委托司法鉴定机构进行交通事故伤残程度鉴定的委托书模板',
        format: 'docx',
        difficulty: 'easy',
        tags: ['交通事故', '伤残鉴定', '委托书'],
        downloads: 1789,
        updatedAt: '2024-01-10'
      },
      {
        id: 6,
        name: '交通事故保险理赔催收律师函',
        category: 'letter',
        description: '向保险公司催收交通事故理赔款的专业律师函模板',
        format: 'docx',
        difficulty: 'easy',
        tags: ['交通事故', '保险理赔', '律师函'],
        downloads: 2150,
        updatedAt: '2024-01-08'
      },
      {
        id: 7,
        name: '交通事故责任认定复核申请书',
        category: 'application',
        description: '对交警部门作出的事故责任认定不服时的复核申请书模板',
        format: 'docx',
        difficulty: 'medium',
        tags: ['交通事故', '责任认定', '复核申请'],
        downloads: 1320,
        updatedAt: '2024-01-05'
      },
      {
        id: 8,
        name: '交通事故死亡赔偿协议书',
        category: 'agreement',
        description: '交通事故致人死亡案件的赔偿协议书模板，包含各项赔偿条款',
        format: 'docx',
        difficulty: 'hard',
        tags: ['交通事故', '死亡赔偿', '协议书'],
        downloads: 890,
        updatedAt: '2024-01-03'
      }
    ])
    
    // 计算属性
    const filteredTemplates = computed(() => {
      let result = templates.value
      
      // 分类筛选
      if (activeCategory.value !== 'all') {
        result = result.filter(t => t.category === activeCategory.value)
      }
      
      // 搜索筛选
      if (searchKeyword.value) {
        const keyword = searchKeyword.value.toLowerCase()
        result = result.filter(t =>
          t.name.toLowerCase().includes(keyword) ||
          t.description.toLowerCase().includes(keyword) ||
          t.tags.some(tag => tag.toLowerCase().includes(keyword))
        )
      }
      
      // 格式筛选
      if (filters.format) {
        result = result.filter(t => t.format === filters.format)
      }
      
      // 复杂度筛选
      if (filters.difficulty) {
        result = result.filter(t => t.difficulty === filters.difficulty)
      }
      
      return result
    })
    
    // 方法
    const refreshData = () => {
      ElMessage.success('数据已刷新')
    }
    
    const setActiveCategory = (category) => {
      activeCategory.value = category
      currentPage.value = 1
    }
    
    const getCategoryCount = (category) => {
      if (category === 'all') return templates.value.length
      return templates.value.filter(t => t.category === category).length
    }
    
    const getCategoryName = (category) => {
      const cat = categories.find(c => c.key === category)
      return cat ? cat.name : category
    }
    
    const applyFilters = () => {
      currentPage.value = 1
    }
    
    const clearFilters = () => {
      Object.assign(filters, {
        format: '',
        difficulty: ''
      })
      searchKeyword.value = ''
      activeCategory.value = 'all'
      currentPage.value = 1
    }
    
    const getFormatIcon = (format) => {
      const iconMap = {
        docx: 'fas fa-file-word text-blue-600',
        pdf: 'fas fa-file-pdf text-red-600',
        xlsx: 'fas fa-file-excel text-green-600',
        txt: 'fas fa-file-alt text-gray-600'
      }
      return iconMap[format] || 'fas fa-file'
    }
    
    const previewTemplate = (template) => {
      router.push(`/lawyer/template/${template.id}`)
    }
    
    const handleAction = ({ action, template }) => {
      switch (action) {
        case 'download':
          downloadTemplate(template)
          break
        case 'edit':
          editTemplate(template)
          break
        case 'copy':
          copyTemplate(template)
          break
        case 'delete':
          deleteTemplate(template)
          break
      }
    }
    
    const downloadTemplate = (template) => {
      template.downloads++
      ElMessage.success(`${template.name} 下载成功`)
    }
    
    const editTemplate = (template) => {
      router.push(`/lawyer/template/${template.id}/edit`)
    }
    
    const copyTemplate = (template) => {
      const newTemplate = {
        ...template,
        id: Math.max(...templates.value.map(t => t.id)) + 1,
        name: `${template.name} - 副本`,
        downloads: 0,
        updatedAt: dayjs().format('YYYY-MM-DD')
      }
      templates.value.unshift(newTemplate)
      ElMessage.success('模板复制成功')
    }
    
    const deleteTemplate = async (template) => {
      try {
        await ElMessageBox.confirm('确定要删除这个模板吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const index = templates.value.findIndex(t => t.id === template.id)
        if (index > -1) {
          templates.value.splice(index, 1)
          ElMessage.success('模板删除成功')
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }
    
    const handleFileUpload = (file) => {
      newTemplate.file = file
      return false // 阻止自动上传
    }
    
    const uploadTemplate = () => {
      if (!newTemplate.name || !newTemplate.category || !newTemplate.file) {
        ElMessage.error('请填写必填字段并选择文件')
        return
      }
      
      const id = Math.max(...templates.value.map(t => t.id)) + 1
      const fileExt = newTemplate.file.name.split('.').pop().toLowerCase()
      
      templates.value.unshift({
        id,
        name: newTemplate.name,
        category: newTemplate.category,
        description: newTemplate.description,
        format: fileExt,
        difficulty: 'easy',
        tags: newTemplate.tagsInput ? newTemplate.tagsInput.split(',').map(tag => tag.trim()) : [],
        downloads: 0,
        updatedAt: dayjs().format('YYYY-MM-DD')
      })
      
      showUploadDialog.value = false
      Object.assign(newTemplate, {
        name: '',
        category: '',
        description: '',
        tagsInput: '',
        file: null
      })
      
      ElMessage.success('模板上传成功')
    }
    
    const formatDate = (date) => {
      return dayjs(date).format('YYYY-MM-DD')
    }
    
    return {
      searchKeyword,
      activeCategory,
      currentPage,
      pageSize,
      showUploadDialog,
      filters,
      newTemplate,
      categories,
      filteredTemplates,
      refreshData,
      setActiveCategory,
      getCategoryCount,
      getCategoryName,
      applyFilters,
      clearFilters,
      getFormatIcon,
      previewTemplate,
      handleAction,
      handleFileUpload,
      uploadTemplate,
      formatDate
    }
  }
}
</script>

<style scoped>
.document-templates {
  padding: 24px;
  background-color: #f9fafb;
  min-height: 100vh;
}

/* 页面头部 */
.page-header {
  background: white;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title {
  font-size: 28px;
  font-weight: bold;
  color: #1f2937;
  margin: 0 0 8px 0;
}

.page-subtitle {
  color: #6b7280;
  margin: 0;
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

/* 分类导航 */
.category-nav {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.category-tabs {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.category-tab {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  background: #f8fafc;
  color: #6b7280;
}

.category-tab:hover {
  background: #e2e8f0;
  color: #374151;
}

.category-tab.active {
  background: #3b82f6;
  color: white;
}

.category-tab .count {
  background: rgba(255, 255, 255, 0.2);
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
}

/* 筛选区域 */
.filter-section {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.filter-content {
  display: flex;
  gap: 16px;
  align-items: center;
}

.search-box {
  flex: 1;
  max-width: 400px;
}

.filter-controls {
  display: flex;
  gap: 12px;
  align-items: center;
}

/* 模板列表 */
.templates-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.templates-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.template-card {
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  padding: 20px;
  transition: all 0.3s ease;
  cursor: pointer;
  background: #fafafa;
}

.template-card:hover {
  border-color: #3b82f6;
  box-shadow: 0 4px 16px rgba(59, 130, 246, 0.1);
  transform: translateY(-2px);
}

.template-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.template-icon i {
  font-size: 32px;
}

.template-actions {
  cursor: pointer;
}

.el-dropdown-link {
  color: #6b7280;
  font-size: 16px;
  cursor: pointer;
}

.template-title {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 8px 0;
  line-height: 1.4;
}

.template-description {
  color: #6b7280;
  font-size: 14px;
  line-height: 1.5;
  margin: 0 0 16px 0;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.template-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 16px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #6b7280;
}

.template-footer {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
}

.template-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.tag-item {
  margin: 0;
}

.template-date {
  font-size: 12px;
  color: #9ca3af;
}

.pagination-section {
  display: flex;
  justify-content: center;
  padding-top: 24px;
  border-top: 1px solid #e5e7eb;
}

/* 上传对话框 */
.upload-demo {
  width: 100%;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .header-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .filter-content {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-controls {
    justify-content: center;
    flex-wrap: wrap;
  }
  
  .templates-grid {
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  }
}

@media (max-width: 768px) {
  .document-templates {
    padding: 16px;
  }
  
  .templates-grid {
    grid-template-columns: 1fr;
  }
  
  .category-tabs {
    justify-content: center;
  }
}
</style>
